import { ipcMain } from "electron";
import type { IpcInvokeReturn } from "@common/ipc-channel-types.ts";

export function defineChannel(channel: string, handler: (...args: any[]) => any) {
  const registerChannel = `ipc://${channel}`;
  ipcMain.handle(registerChannel, (_, ...args: any[]) => {
    return new Promise(async resolve => {
      const resp: IpcInvokeReturn = {};
      try {
        resp.data = await handler(...args);
      } catch (e: any) {
        resp.error = e?.message ?? e?.toString() ?? "Internal error";
      }
      resolve(resp);
    });
  });
  console.log(`[ipc-channel] Registered service: ${registerChannel}`);
}
